﻿using AntUnion.FrameWork.Model.Models;
using AntUnion.FrameWork.Model.ModelsExt;
using AntUnion.FrameWork.Util;
using AntUnion.FrameWork.Web.Common;
using AntUnion.FrameWork.Web.Extend;
using AntUnion.FrameWork.Web.Filter;
using AntUnion.FrameWork.Web.Service;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.IdentityModel.Tokens.Jwt;
using System.IO;
using System.Linq;
using System.Net.Http.Headers;
using System.Reflection;
using System.Threading.Tasks;

namespace AntUnion.FrameWork.Web.Controllers
{
    [TypeFilter(typeof(MyExceptionFilter))]
    public class BaseController : Controller
    {
        public static string BaseUrl = DefaultCache.SystemConfig()["base_url"].ToString();
        public static string PATH = "upload";
        public CrmService crmService = new CrmService();
        public LogService logService = new LogService();
        public RoleService roleService = new RoleService();
        public AssetsServer assetsServer = new AssetsServer();
        public MeunService meunService = new MeunService();
        public Mt5Service mt5Service = new Mt5Service();
        public PublicService publicService = new PublicService();
        public ReportServer reportServer = new ReportServer();
        public ReferralService referralService = new ReferralService();
        public BaseController()
        {
        }

        #region  基本数值
        public const int PAGE = 1;
        public const int LIMIT = 20;

        public int expires = 60;
        #endregion

        #region 非接口部分

        #endregion

        #region 公共方法

        #region cookie 读写
        /// <summary>
        /// 设置本地cookie
        /// </summary>
        /// <param name="key">键</param>
        /// <param name="value">值</param>  
        /// <param name="minutes">过期时长，单位：分钟</param>      
        protected void SetCookies(string key, string value, int minutes = 0)
        {
            if (minutes > 0)
            {
                HttpContext.Response.Cookies.Append(key, value, new CookieOptions
                {
                    Expires = DateTimeUtil.Now.AddMinutes(minutes)
                });
            }
            else
            {
                HttpContext.Response.Cookies.Append(key, value);
            }
        }
        /// <summary>
        /// 删除指定的cookie
        /// </summary>
        /// <param name="key">键</param>
        protected void DeleteCookies(string key)
        {
            HttpContext.Response.Cookies.Delete(key);
        }

        /// <summary>
        /// 获取cookies
        /// </summary>
        /// <param name="key">键</param>
        /// <returns>返回对应的值</returns>
        protected string GetCookies(string key)
        {
            HttpContext.Request.Cookies.TryGetValue(key, out string value);
            if (string.IsNullOrEmpty(value))
                value = string.Empty;
            return value;
        }
        #endregion

        #region session 读写

        /// <summary>
        /// 设置session
        /// </summary>
        /// <param name="key">键</param>
        /// <param name="value">值</param>    
        protected void SetSessions(string key, object value)
        {
            HttpContext.Session.Set(key, ByteConvertUtil.Serialize(value));
        }

        /// <summary>
        /// 获取session
        /// </summary>
        /// <param name="key">键</param>   
        protected T GetSession<T>(string key)
        {
            HttpContext.Session.TryGetValue(key, out byte[] result);
            if (result != null)
                return (T)ByteConvertUtil.Deserialize<T>(result);
            return default;
        }

        /// <summary>
        /// 删除指定的cookie
        /// </summary>
        /// <param name="key">键</param>
        protected void DeleteSessions(string key)
        {
            HttpContext.Session.Remove(key);
        }

        #endregion

        #region 获取客户端IP

        protected string GetIp()
        {
            return HttpContext.Connection.RemoteIpAddress.ToString();
        }

        #endregion


        /// <summary>
        /// 请求过滤处理
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            filterContext.HttpContext.Session.TryGetValue("CrmUser", out byte[] result);
            if (result == null)
            {

                using (mtContext mtContext = new mtContext())
                {
                    // 从数据库获取要跳转的页面
                    TbSystemConfig systemMaintenanceConfig = mtContext.TbSystemConfigs.Where(k => k.Language == "Public" && k.MenuName == "systemMaintenance" && k.Status == true && k.ConfigTab == 1).FirstOrDefault();
                    // 根据数据库值跳转到指定页面
                    if (systemMaintenanceConfig != null && systemMaintenanceConfig.Value == "1")
                    {
                        filterContext.Result = new RedirectResult("~/Error/SystemMaintenance");
                        return;
                    }
                }

                string ip = HttpContext.Connection.RemoteIpAddress.ToString();
                string ipAddress = "";
                if (ip != "::1")
                {
                    string[] ips = ip.Split('.');
                    if (ips.Length == 4)
                    {
                        try
                        {
                            IPModel iPModel = HttpUtil.HttpGet($"http://whois.pconline.com.cn/ipJson.jsp?ip={ip}&json=true").ToObject<IPModel>();
                            ipAddress = iPModel.addr;
                        }
                        catch
                        {
                            ipAddress = "";
                        }
                    }
                }
                string[] loginInfo = GetCookies("CrmUser").Split("|");
                if (loginInfo != null && loginInfo.Length == 2)
                {
                    string UserPwd = SecurityUtil.EncryptPwd(loginInfo[1]);
                    CrmUser crmUser = crmService.GetCrmUser(loginInfo[0], UserPwd, ip);
                    if (crmUser != null)
                    {
                        if (crmUser.State == 1)
                        {
                            //记录日志
                            logService.AddLoginLogs(filterContext.HttpContext, crmUser.LoginName, crmUser.Id, 1, "loginSucceeded", ip, ipAddress, 1);
                            CrmUserModel model = new CrmUserModel
                            {
                                Id = crmUser.Id,
                                Name = crmUser.Name,
                                LoginName = crmUser.LoginName,
                                State = crmUser.State,
                                SessionId = HttpContext.Session.Id
                            };
                            SetSessions("CrmUser", model);
                            SetCookies("CrmUser", loginInfo[0] + "|" + loginInfo[1], expires * 60);
                            crmUser.LastIp = ip;
                            crmUser.LastTime = DateTimeUtil.Now;
                            using (mtContext _context = new mtContext())
                            {
                                _context.SaveChanges();
                            }
                        }
                        else
                        {
                            logService.AddLoginLogs(filterContext.HttpContext, loginInfo[0], crmUser.Id, 0, "loginManagementSystemFailed", ip, ipAddress, 1);
                            filterContext.Result = new RedirectResult("~/Login/NeedLogin");
                            return;
                        }
                    }
                    else
                    {
                        logService.AddLoginLogs(filterContext.HttpContext, loginInfo[0], 0, 0, "loginManagementSystemFailed", ip, ipAddress, 1);
                        filterContext.Result = new RedirectResult("~/Login/NeedLogin");
                        return;
                    }
                }
                else
                {
                    filterContext.Result = new RedirectResult("~/Login/NeedLogin");
                    return;
                }
            }
            else
            {
                using (mtContext mtContext = new mtContext())
                {
                    // 从数据库获取要跳转的页面
                    TbSystemConfig systemMaintenanceConfig = mtContext.TbSystemConfigs.Where(k => k.Language == "Public" && k.MenuName == "systemMaintenance" && k.Status == true && k.ConfigTab == 1).FirstOrDefault();
                    // 根据数据库值跳转到指定页面
                    if (systemMaintenanceConfig != null && systemMaintenanceConfig.Value == "1")
                    {
                        filterContext.Result = new RedirectResult("~/Error/SystemMaintenance");
                        return;
                    }
                }
                //添加操作日志
                logService.AddOperatorLogs(filterContext, CrmUser.LoginName, CrmUser.Id, 1);
            }
            base.OnActionExecuting(filterContext);
        }
        #endregion

        #region 图片上传

        [HttpPost]
        [RequestSizeLimit(52428800)]
        public JsonResult UploadFile(int? width, int? height, int? type)
        {
            Result re = new Result();
            try
            {
                var file = Request.Form.Files[0];
                long size = file.Length;
                if (size > 52428800)
                {
                    re.Code = 1;
                    re.Msg = "上传的文件不能大于50M！";
                }
                else
                {
                    FileData data = new FileData();
                    var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
                    //没有合适的格式
                    string extName = Path.GetExtension(fileName.ToString()).ToLower();
                    string src = "";
                    if (ImageFactory.GetImgFormat().ContainsKey(extName))
                    {
                        Image image = Image.FromStream(file.OpenReadStream());
                        src = ImageFactory.SaveImage(image, "upload", fileName, width, height);
                    }
                    else
                    {
                        src = ImageFactory.SaveFile(file, fileName, PATH);
                    }
                    if (type == 1)
                    {
                        src = BaseUrl + src;
                    }
                    data.Src = src;
                    re.Data = data;
                    re.Code = 0;
                    re.Msg = "uploadSuccess";
                }
            }
            catch (Exception ex)
            {
                re.Code = -1;
                re.Msg = ex.Message;
            }
            return new JsonResult(re);
        }

        #endregion

#pragma warning disable CS0109 // 成员“BaseController.CrmUser”不会隐藏可访问成员。不需要关键字 new。
        public new CrmUserModel CrmUser
#pragma warning restore CS0109 // 成员“BaseController.CrmUser”不会隐藏可访问成员。不需要关键字 new。
        {
            get { return GetSession<CrmUserModel>("CrmUser"); }
        }

        #region 获取温馨提示
        /// <summary>
        /// 获取温馨提示
        /// </summary>
        /// <param name="language"></param>
        /// <returns></returns>
        [HttpGet]
        public JsonResult GetWarmPrompt(string warmPromptKey, string language = "user-zh-CN")
        {
            Result re = new Result();
            try
            {
                string defaultLanguage = "zh-CN";
                if (language == "user-en-US")
                {
                    defaultLanguage = "en-US";
                }
                using (mtContext mtContext = new mtContext())
                {
                    TbSystemConfig systemConfig = mtContext.TbSystemConfigs.Where(k => k.Language == defaultLanguage && k.MenuName == warmPromptKey && k.Status == true && k.ConfigTab == 1).FirstOrDefault();
                    if (systemConfig != null)
                    {
                        re.Code = 1;
                        re.Data = systemConfig.Value;
                    }
                    else
                    {
                        re.Code = 1;
                        re.Data = null;
                    }
                }
            }
            catch (Exception ex)
            {
                re.Code = -1;
                re.Msg = ex.Message;
            }
            return new JsonResult(re);
        }
        #endregion
    }
}
